PowerShell Training · Topic 1

Limpiar nombres de archivos masivamente sin miedo

Un ejercicio práctico para aprender cómo crear data sintética, ejecutar una acción real en PowerShell y verificar el resultado antes de avanzar al próximo caso.

Clean file names in bulk with confidence

A hands-on exercise to learn how to create synthetic data, run a real PowerShell action, and verify the result before moving to the next case.

⚠️ Advertencia crítica antes de correr cualquier script

No ejecutes este tipo de script en un ambiente de producción, carpeta real, servidor compartido, unidad de red o sistema institucional sin autorización formal.

PowerShell es una herramienta poderosa: un comando de renombrado masivo puede modificar cientos o miles de archivos en segundos. En una carpeta equivocada, eso puede causar pérdida de trazabilidad, fallos en procesos automáticos, interrupciones operativas o incidentes de ciberseguridad.

Regla obligatoria del training: primero se trabaja con data sintética, luego se valida con una muestra pequeña, después se prueba con -WhatIf cuando aplique, y solo entonces se considera ejecutar en datos reales siguiendo los protocolos de la organización.

  • Permisos: usa solamente carpetas donde tengas autorización explícita.
  • Backups: confirma que exista copia de seguridad o posibilidad real de recuperación.
  • Cybersecurity: cumple las políticas internas, controles de acceso, change management y principios de menor privilegio.
  • Producción: nunca ejecutes scripts masivos directamente sobre producción sin revisión, aprobación y plan de reversa.

⚠️ Critical warning before running any script

Do not run this type of script in a production environment, real folder, shared server, network drive, or institutional system without formal authorization.

PowerShell is a powerful tool: a bulk rename command can modify hundreds or thousands of files in seconds. In the wrong folder, it can break traceability, disrupt automated processes, create operational issues, or trigger cybersecurity incidents.

Mandatory training rule: start with synthetic data, validate with a small sample, test with -WhatIf when applicable, and only then consider real data while following your organization’s protocols.

  • Permissions: use only folders where you have explicit authorization.
  • Backups: confirm that a backup or real recovery option exists.
  • Cybersecurity: follow internal policies, access controls, change management, and least-privilege principles.
  • Production: never run bulk scripts directly on production without review, approval, and rollback planning.

Objetivo del Topic 1

El objetivo es eliminar una letra innecesaria al inicio de muchos archivos .jpg. En este caso, vamos a quitar la letra P cuando aparece al principio del nombre.

01 · Crear data
02 · Ejecutar limpieza
03 · Verificar resultado
Idea central: este ejercicio enseña el patrón base de muchos flujos reales: listar archivos, transformar nombres y validar que el cambio fue correcto.

Topic 1 Objective

The goal is to remove an unnecessary starting letter from many .jpg files. In this case, we remove the letter P when it appears at the beginning of the file name.

01 · Create data
02 · Run cleanup
03 · Verify result
Core idea: this exercise teaches the basic pattern behind many real workflows: list files, transform names, and validate the change.

Ruta de trabajo

Para mantener el training limpio, todo se ejecuta dentro de una carpeta controlada:

Working folder

To keep the training clean, everything runs inside one controlled folder:

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\Powershell\Topic 1"
Importante: no practiques este tipo de comando en carpetas reales de producción. Trabaja primero con data sintética, permisos claros, backup y aprobación según los protocolos de ciberseguridad.
Important: do not practice this type of command in real production folders. Work first with synthetic data, clear permissions, backups, and approval under cybersecurity protocols.

Qué vamos a aprender

  • Crear archivos falsos para practicar.
  • Usar Get-ChildItem para listar archivos.
  • Usar el pipeline | para pasar objetos a otro comando.
  • Usar Rename-Item para renombrar archivos.
  • Usar -replace "^P", "" para quitar solo la P inicial.

What you will learn

  • Create fake files for practice.
  • Use Get-ChildItem to list files.
  • Use the pipeline | to pass objects to another command.
  • Use Rename-Item to rename files.
  • Use -replace "^P", "" to remove only the starting P.
01

Script 1 — Crear data sintética

Este script crea una carpeta de práctica y genera archivos .jpg vacíos con una P al inicio. No son fotos reales; son archivos de entrenamiento para practicar el cambio de nombre sin riesgo.

Script 1 — Create synthetic data

This script creates a practice folder and generates empty .jpg files with a starting P. They are not real photos; they are training files used to practice renaming safely.

# Topic 1 - Crear data sintética para limpiar nombres de archivos masivamente

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\Powershell\Topic 1"

# Crear carpeta si no existe
New-Item -Path $BasePath -ItemType Directory -Force | Out-Null

# Crear archivos JPG de práctica con una P al inicio
$Files = @(
    "P001.jpg",
    "P002.jpg",
    "P003.jpg",
    "P004.jpg",
    "P005.jpg",
    "PEmployee_1001.jpg",
    "PEmployee_1002.jpg",
    "PPhoto_John_Smith.jpg",
    "PPhoto_Maria_Garcia.jpg",
    "PIMG_20260101.jpg",
    "PIMG_20260102.jpg",
    "PScan_ABC123.jpg",
    "PBadge_9001.jpg",
    "PProfile_555.jpg",
    "PDocument_789.jpg"
)

foreach ($File in $Files) {
    New-Item -Path (Join-Path $BasePath $File) -ItemType File -Force | Out-Null
}

Write-Host "Data sintética creada en:" $BasePath
Write-Host ""
Write-Host "Archivos creados:"
Get-ChildItem $BasePath -Filter "*.jpg" | Select-Object Name
New-ItemJoin-PathforeachGet-ChildItem
02

Script 2 — Ejecutar la limpieza

Este es el comando principal del topic. Busca todos los archivos .jpg en la carpeta y renombra cada uno quitando la P inicial.

Script 2 — Run the cleanup

This is the main command of the topic. It finds all .jpg files in the folder and renames each one by removing the starting P.

Get-ChildItem "$env:USERPROFILE\Documents\AI Practical Training\Powershell\Topic 1" -Filter "*.jpg" |
Rename-Item -NewName { $_.Name -replace "^P", "" }
Lectura del comando: “Dame todos los JPG de esta carpeta y, para cada archivo, cambia su nombre reemplazando la P del inicio por nada”.
How to read the command: “Give me all JPG files in this folder and, for each file, change its name by replacing the starting P with nothing.”

Antes y después esperado

Antes
P001.jpg
PEmployee_1001.jpg
PPhoto_John_Smith.jpg
PIMG_20260101.jpg
Después
001.jpg
Employee_1001.jpg
Photo_John_Smith.jpg
IMG_20260101.jpg

Expected before and after

Before
P001.jpg
PEmployee_1001.jpg
PPhoto_John_Smith.jpg
PIMG_20260101.jpg
After
001.jpg
Employee_1001.jpg
Photo_John_Smith.jpg
IMG_20260101.jpg

Qué significa ^P

En una expresión regular, el símbolo ^ significa “inicio del texto”. Por eso ^P significa “la P que está al comienzo del nombre”.

Eso evita borrar letras P que estén en otra posición del archivo.

What ^P means

In a regular expression, the ^ symbol means “start of the text.” So ^P means “the P at the beginning of the name.”

This prevents removing P letters that appear somewhere else in the file name.

"PPhoto_John_Smith.jpg" -replace "^P", ""
# Resultado: Photo_John_Smith.jpg
03

Script 3 — Verificar resultados

La verificación es parte del entrenamiento. Después de modificar archivos, siempre conviene listar el resultado final para confirmar que la acción fue correcta.

Script 3 — Verify results

Verification is part of the training. After changing files, it is always a good practice to list the final result and confirm the action worked correctly.

Get-ChildItem "$env:USERPROFILE\Documents\AI Practical Training\Powershell\Topic 1" -Filter "*.jpg" |
Select-Object Name

Comando clave 1

Get-ChildItem lista archivos y carpetas. Aquí lo usamos con -Filter "*.jpg" para trabajar solo con imágenes JPG.

Key command 1

Get-ChildItem lists files and folders. Here we use -Filter "*.jpg" to work only with JPG images.

Comando clave 2

El pipeline | pasa cada archivo encontrado hacia el siguiente comando, como si fuera una línea de producción.

Key command 2

The pipeline | passes each found file into the next command, like a production line.

Comando clave 3

Rename-Item cambia el nombre. La variable $_ representa el archivo actual dentro del pipeline.

Key command 3

Rename-Item changes the name. The $_ variable represents the current file inside the pipeline.

Buena práctica para producción

Antes de renombrar archivos reales, puedes probar el impacto con -WhatIf. PowerShell te muestra qué haría sin ejecutar el cambio.

Good practice for production

Before renaming real files, you can test the impact with -WhatIf. PowerShell shows what it would do without applying the change.

Get-ChildItem "$env:USERPROFILE\Documents\AI Practical Training\Powershell\Topic 1" -Filter "*.jpg" |
Rename-Item -NewName { $_.Name -replace "^P", "" } -WhatIf
Regla de oro: primero crear data sintética, luego probar con -WhatIf, después ejecutar, y al final verificar.
Golden rule: create synthetic data first, test with -WhatIf, then execute, and finally verify.

Cierre del Topic 1

Este primer caso parece sencillo, pero contiene una base poderosa: automatizar una tarea repetitiva de limpieza de archivos. El mismo patrón se puede ampliar para quitar espacios dobles, guiones raros, prefijos, sufijos, caracteres especiales o preparar archivos antes de cargarlos a otro sistema.

Mensaje para el estudiante: PowerShell no es solo código. Es una herramienta para convertir trabajo manual repetitivo en procesos controlados, verificables y enseñables.

Topic 1 Wrap-up

This first case looks simple, but it contains a powerful foundation: automating a repetitive file-cleaning task. The same pattern can be expanded to remove double spaces, unusual dashes, prefixes, suffixes, special characters, or prepare files before loading them into another system.

Message for the student: PowerShell is not just code. It is a tool to turn repetitive manual work into controlled, verifiable, and teachable processes.